﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Net;
using System.Web.SessionState;
using System.Runtime.InteropServices;

public partial class index : Page, IRequiresSessionState
{
    MyDbHelper mydb = new MyDbHelper();
    DbHelper db = new DbHelper();
    [DllImport("Iphlpapi.dll")]
    private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
    [DllImport("Ws2_32.dll")]
    private static extern Int32 inet_addr(string ip);

    protected void Page_Load(object sender, EventArgs e)
    {
        string aciton = Request.Params["aciton"];
        switch (aciton)
        {
            case "GetOnline":
                GetOnline();
                break;
            case "Login":
                UserLogin();
                break;
            case "GetUser":
                GetUserInfo();
                break;
            case "LoginOut":
                LoginOut();
                break;
            case "get_modles":
                GetModules();
                break;
            case "LoadMenu":
                LoadMenu();
                break;
            case "lodshoplist":
                lodshoplist();
                break;
            case "GetUserOnlineList":
                GetUserOnlineList();
                break;
            case "first_uppwd":
                first_uppwd();
                break;
        }
    }

    private void first_uppwd()
    {
       //第一次登录修改密码。
        string sbr = "";
        string usercode = Request.Params["UserCode"];
        string pwd = Request.Params["Pwd"];
        string des_pwd = SDKSecurity.DESEncrypt(pwd, "km141201");
        string sql = "update Sys_LoginUser set UpPwd = 1,ModifyDate=getdate(),upassword = '" + des_pwd + "' where usercode='" + usercode + "'";
        if (mydb.DM_ExecuteNonQuery(sql) != -1)
        {
            sbr = "{\"status\":\"1\",\"msg\":\"操作成功！\"}";
        }
        else
        {
            sbr = "{\"status\":\"0\",\"msg\":\"操作失败，请系统IT！\"}";
        }
        Response.Write(sbr);
        Response.End();
    }

    private void GetUserOnlineList()
    {
        DataTable userTable = null;
        userTable = (DataTable)Application["OnlineUsers"];
        if (userTable != null)
        {
            if (userTable.Rows.Count > 0)
            {
                string sbr = "";
                sbr = "[";
                foreach (DataRow dr in userTable.Rows)
                {
                    sbr += "{\"UserCode\":\"" + dr["UserCode"]
                        + "\",\"UserName\":\"" + dr["UserName"]
                        + "\",\"OSName\":\"" + dr["OSName"]
                        + "\"},";
                }
                sbr = sbr.TrimEnd(',') + "]";
                Response.Write(sbr);
                Response.End();
            }
            else
            {
                Response.Write("NO_DATA");
                Response.End();
            }
        }
    }

    private void lodshoplist()
    {
        string shopname = Request.Params["shopname"];
        string str = "";
        if (shopname != "")
        {
            str += " and shopname like '%" + shopname + "%'";
        }
        DataSet ds = db.DM_GetDateSet("select * from Bas_Shop where 1=1 " + str + " order by shopcode");
        if (ds.Tables[0].Rows.Count >0)
        {
            string sbr = "";
            sbr = "[";
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                sbr += "{\"shopname\":\"" + dr["shopname"]
                    + "\",\"shopid\":\"" + dr["shopid"]
                    + "\"},";
            }
            sbr = sbr.TrimEnd(',') + "]";
            Response.Write(sbr);
            Response.End();
        }
        else
        {
            Response.Write("NO_DATA");
            Response.End();
        }

    }

    private string LoadChildMenu(string parentid)
    {
        string sql = @"select a.* from sys_modules a left join Sys_ModuleRights b on b.mid = a.mid
                        where b.userid = "+Session["UserID"]+" and b.M_Browse =1 and parentid = "+parentid+" order by mindx";
        DataSet ds = mydb.DM_GetDateSet(sql);
        if (ds.Tables[0].Rows.Count > 0)
        {
            string sbr = "";
            sbr = "[";
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                sbr += "{\"modulecode\":\"" + dr["modulecode"]
                 + "\",\"modulename\":\"" + dr["modulename"]
                 + "\",\"mid\":\"" + dr["mid"]
                 + "\",\"mindx\":\"" + dr["mindx"]
                 + "\",\"weburl\":\"" + dr["weburl"]
                 + "\"},";
            }
            sbr = sbr.TrimEnd(',') +"]";
            return sbr;

        }
        else
        {
            return "";
        }
    }

    private void LoadMenu()
    {
        string sql = "select * from sys_modules where parentid = 0 order by mindx";
        DataSet ds = mydb.DM_GetDateSet(sql);
        if (ds.Tables[0].Rows.Count > 0)
        {
            string sbr = "";
            string child_sbr = "";
            sbr = "[";
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                child_sbr = LoadChildMenu(dr["mid"].ToString());
                if (child_sbr != "")
                {
                    sbr += "{\"modulecode\":\"" + dr["modulecode"]
                     + "\",\"modulename\":\"" + dr["modulename"]
                     + "\",\"mid\":\"" + dr["mid"]
                     + "\",\"mindx\":\"" + dr["mindx"]
                     + "\",\"weburl\":\"" + dr["weburl"];
                    if (child_sbr != "")
                    {
                        sbr += "\",\"childNode\":" + child_sbr + "},";
                    }
                    else
                    {
                        sbr += "\"},";
                    }
                }
            }
            sbr = sbr.TrimEnd(',') + "]";
            Response.Write(sbr);
            Response.End();

        }
        else
        {
            Response.Write("NO_DATA");
            Response.End();
        }
    }

    private void GetModules()
    {
        string sql = "select * from sys_modules where parentid = 0";
        DataSet ds = mydb.DM_GetDateSet(sql);
        if (ds.Tables[0].Rows.Count > 0)
        {
            string sbr = "";
            sbr = "[";
            string child_sbr = "";
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                child_sbr = GetChildModules(dr["parentid"].ToString());
                sbr += "{\"text\":\"" + dr["modulename"]
                 + "\",\"href\":\"#" + dr["modulename"]
                 + "\",\"tags\":[\"" + dr["parentid"]
                 + "\"]},";
            }
            sbr = sbr.TrimEnd(',') + "]";
            Response.Write(sbr);
            Response.End();

        }
    }

    private string GetChildModules(string parentid)
    {
        return "";
    }

    private void LoginOut()
    {
        //Session.Clear();//从Session状态集合中移除所有的键和值。 
        Session.Abandon();//取消当前Session会话  
    }

    private void GetUserInfo()
    {
        if (Session["UserCode"] == null || Session["UserCode"].ToString() == "")
        {
            Response.Write("NOUSER");
            Response.End();
        }
        else
        {
            string uppwd = mydb.DM_GetExecuteScalarObj("select uppwd from sys_loginuser where usercode = '" + Session["UserCode"] + "'").ToString();
            string sbr = "";
            sbr = "[";

            sbr += "{\"UserCode\":\"" + Session["UserCode"]
                    + "\",\"UserName\":\"" + Session["UserName"]
                    + "\",\"UpPwd\":\"" + uppwd
                    + "\"},";
            sbr = sbr.TrimEnd(',') + "]";
            Response.Write(sbr);
            Response.End();
        }
        return;
    }

    private void GetOnline()
    {
        DataTable userTable = null;
        userTable = (DataTable)Application["OnlineUsers"];
        if (userTable != null)
        {
            Response.Write(userTable.Rows.Count.ToString());
            Response.End();
        }
        else
        {
            //Response.Write(Application["useronline"]);//返回礼品列表
            Response.Write("0");
            Response.End();
        }
        
    }

    private void UserLogin()
    {
        string ucode = Request.Params["UserCode"];
        string pwd = Request.Params["UserPwd"];
        string type = Request.Params["LoginType"];
        DataSet ds = mydb.DM_GetDateSet("select * from sys_loginuser where usercode ='" + ucode + "'");
        if (ds.Tables[0].Rows.Count > 0)
        {
            DataRow dr = ds.Tables[0].Rows[0];

            //查检密码
            string des_wpd = "";
            //if (bool.Parse(dr["UpPwd"].ToString()))
            //    des_wpd = SDKSecurity.DESDecrypt(dr["upassword"].ToString(), "km141201");
            //else
            //    des_wpd = dr["upassword"].ToString();
            des_wpd = SDKSecurity.DESDecrypt(dr["upassword"].ToString(), "km141201");
            if (pwd.ToLower() != des_wpd.ToLower())
            {
                Response.Write("err_text");
                Response.End();
                return;
            }

            System.Data.DataTable userTable = (System.Data.DataTable)Application["OnlineUsers"];
            if (userTable == null)
                return;
            System.Data.DataRow[] curRow = userTable.Select("UserCode='" + ucode+ "'");

            if (curRow.Length > 0)
            {
                Response.Write("user_lock");
                Response.End();
                return;
            }
            if (bool.Parse(dr["block"].ToString()))
            {
                Session.Clear();
                Session["UserID"] = dr["userid"];
                Session["UserCode"] = dr["usercode"];
                Session["UserName"] = dr["username"];

                string sbr = "";
                sbr = "[";

                sbr += "{\"UserCode\":\"" + dr["usercode"]
                        + "\",\"UserName\":\"" + dr["username"]
                        + "\"},";
                sbr = sbr.TrimEnd(',') + "]";

                string userid = dr["userid"].ToString();
                mydb.DM_ExecuteNonQuery("update sys_loginuser set islogined = 1,logincount=isnull(logincount,0)+1 where userid=" + userid);
                InsLoginLog(userid, type, Request.UserHostAddress);

                Response.Write(sbr);
                Response.End();
            }
            else
            {
                Response.Write("user_stop");
                Response.End();
            }
        }
        else
        {
            Response.Write("err_text");
            Response.End();
        }
    }
    public void InsLoginLog(string UserID, string LoginType,string userIP)
    {
        string sql = @"insert into sys_loginlog(userid,logintype,loginip)
                        values(" + UserID + ",'" + LoginType + "','" + userIP + "')";
        mydb.DM_ExecuteNonQuery(sql);

        try
        {

            string sessionid = Session.SessionID;

            HttpBrowserCapabilities bc = Request.Browser;

            string osName = "win7";

            //判断操作系统  

            switch (bc.Platform)
            {

                case "WinNT5.1":

                case "WinXP":

                    osName = "Windows XP";

                    break;

                case "WinNT 5.0":

                    osName = "Win2000";

                    break;

                case "WinNT":

                    osName = "Win7";

                    break;

                default:

                    osName = bc.Platform;

                    break;

            }

            string browser = bc.Type;

            System.Data.DataTable userTable = (System.Data.DataTable)Application["OnlineUsers"];

            if (userTable == null)

                return;

            System.Data.DataRow[] curRow = userTable.Select("UserCode='" + Session["UserCode"] + "'");

            if (curRow.Length == 0)
            {

                System.Data.DataRow row = userTable.NewRow();

                row["SessionID"] = sessionid;
                row["UserCode"] = Session["UserCode"];
                row["UserName"] = Session["UserName"];
                row["UserIP"] = userIP;
                row["Browser"] = browser;
                row["OSName"] = osName;
                userTable.Rows.Add(row);
                userTable.AcceptChanges();

                Application.Lock();

                Application["OnlineUsers"] = userTable;

                Application.UnLock();

            }

        }

        catch
        {

        }  
  
    }

    static string GetLocalIp()
    {
        string hostname = Dns.GetHostName();
        IPHostEntry localhost = Dns.GetHostByName(hostname);
        IPAddress localaddr = localhost.AddressList[0];
        return localaddr.ToString();
    }
    //获取MAC地址
    private string GetMac()
    {
        // 在此处放置用户代码以初始化页面
        try
        {
            string userip = Request.UserHostAddress;
            string strClientIP = Request.UserHostAddress.ToString().Trim();
            Int32 ldest = inet_addr(strClientIP); //目的地的ip 
            Int32 lhost = inet_addr("");   //本地服务器的ip 
            Int64 macinfo = new Int64();
            Int32 len = 6;
            int res = SendARP(ldest, 0, ref macinfo, ref len);
            string mac_src = macinfo.ToString("X");
            if (mac_src == "0")
            {
                return "123";
            }
            while (mac_src.Length < 12)
            {
                mac_src = mac_src.Insert(0, "0");
            }
            string mac_dest = "";
            for (int i = 0; i < 11; i++)
            {
                if (0 == (i % 2))
                {
                    if (i == 10)
                    {
                        mac_dest = mac_dest.Insert(0, mac_src.Substring(i, 2));
                    }
                    else
                    {
                        mac_dest = "-" + mac_dest.Insert(0, mac_src.Substring(i, 2));
                    }
                }
            }
            return mac_dest;
        }
        catch (Exception err)
        {
            Response.Write(err.Message);
            return "";
        }

    }
}